import argparse
import os
import subprocess


def detect_silence(input_file, silence_thresh=-40, min_silence_len=10):
    """使用ffmpeg检测静默段"""
    cmd = [
        "ffmpeg",
        "-i",
        input_file,
        "-af",
        f"silencedetect=noise={silence_thresh}dB:d={min_silence_len}",
        "-f",
        "null",
        "-",
    ]

    output = subprocess.run(cmd, capture_output=True, text=True).stderr

    # 解析输出找到静默段
    silence_starts = []
    silence_ends = []
    print(output)
    for line in output.split("\n"):
        if "silence_start" in line:
            silence_starts.append(float(line.split("silence_start: ")[1].split()[0]))
        elif "silence_end" in line:
            silence_ends.append(float(line.split("silence_end: ")[1].split()[0]))
    print(silence_starts, silence_ends)
    return list(zip(silence_starts, silence_ends))


def split_audio(
    input_file, output_dir, silence_thresh=-40, min_silence_len=10, keep_silence=0.5
):
    """根据静默段分割音频"""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 检测静默段
    silences = detect_silence(input_file, silence_thresh, min_silence_len)

    if not silences:
        print("未检测到足够长的静默段")
        return

    # 计算分割点（考虑保留的静默时间）
    current_time = 0
    silences.append((None, None))
    index = 0
    output_files = []
    for start, end in silences:
        index += 1
        start_time = current_time
        if start is None:
            duration = ""  # 到文件末尾
        else:
            duration = start - current_time + keep_silence
            duration = str(duration)
            current_time = end - keep_silence
        output_file = os.path.join(
            output_dir,
            f"{os.path.splitext(os.path.basename(input_file))[0]}_{index}.mp3",
        )
        cmd = ["ffmpeg", "-y", "-i", input_file]
        if start_time > 0:
            cmd.extend(["-ss", str(start_time)])
        if duration:
            cmd.extend(["-t", duration])
        cmd.extend([output_file])
        subprocess.run(cmd, capture_output=True)
        output_files.append(output_file)
        print(f"已生成: {output_file}")
    return output_files


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="当静默时间超过指定时长时分割音频文件。"
    )
    parser.add_argument("input_file", type=str, help="输入音频文件的路径。")
    parser.add_argument("--output_dir", type=str, default=None, help="输出目录的路径。")
    parser.add_argument(
        "--silence_thresh",
        type=int,
        default=-40,
        help="静默阈值，以dB为单位。默认为-40。",
    )
    parser.add_argument(
        "--min_silence_len",
        type=int,
        default=10,
        help="最小静默长度，以秒为单位。默认为10。",
    )
    parser.add_argument(
        "--keep_silence",
        type=float,
        default=0.5,
        help="在分割的音频块开始和结束时保留静默。默认为0.5秒。",
    )

    args = parser.parse_args()
    output_dir = args.output_dir or os.path.dirname(args.input_file)

    split_audio(
        args.input_file,
        output_dir,
        args.silence_thresh,
        args.min_silence_len,
        args.keep_silence,
    )
